import React, { useEffect, useState, useRef } from 'react';
import { message, Input, Table, Modal } from 'antd';
import type { InputRef } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import {
  saveFormModel,
  getPageListFromModel,
  saveForm,
} from '../../../../services/formManagement';

interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}

const columns: ColumnsType<DataType> = [
  {
    title: '名称',
    dataIndex: 'name',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '标识编码',
    dataIndex: 'key',
  },
];

const FormSetting: React.FC = ({ currentElement, modeler }: any) => {
  const inputRef = useRef<InputRef>(null);
  const [tableData, setTableData] = useState([]);
  const [selectedRowKey, setSelectedRowKey] = useState<string[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedInfo, setSelectedInfo] = useState({});
  const [selectedFormInfo, setSelectedFormInfo] = useState({});

  const handleOk = () => {
    let properties: any = {};
    properties['flowable:formKey'] = selectedFormInfo.key;
    updateProperties(properties);
    setSelectedInfo(selectedFormInfo);
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useEffect(() => {
    getFormList();
    getFormInfo(currentElement.businessObject?.formKey);
  }, []);

  // 获取选中表单信息
  const getFormInfo = async (modelKey: string) => {
    if (modelKey) {
      setSelectedRowKey([modelKey]);
      let res = await getPageListFromModel({
        modelKey,
        current: 1,
        pageSize: 5,
      });
      if (res.code !== '000000') {
        return message.error('选中表单信息获取失败');
      }
      setSelectedInfo(res.data[0]);
      setSelectedFormInfo(res.data[0]);
    }
  };

  // 输入框获取焦点
  const onBlur = () => {
    setIsModalOpen(true);
    inputRef.current!.blur();
  };

  // 获取表格信息
  const getFormList = async () => {
    let res = await getPageListFromModel({
      current: 1,
      pageSize: 5,
    });
    if (res.code !== '000000') {
      message.error('获取模型管理表格信息失败');
      return;
    }
    setTableData(res.data);
  };

  // 表格选择回调
  const rowSelection = {
    selectedRowKeys: selectedRowKey,
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setSelectedFormInfo(selectedRows[0]);
      setSelectedRowKey(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.name === 'Disabled User',
      name: record.name,
    }),
  };

  /**
   * 更新元素属性
   * @param { Object } 要更新的属性, 例如 { name: '', id: '' }
   */
  const updateProperties = (properties: any) => {
    delete currentElement.businessObject.loopCharacteristics;
    const modeling = modeler.get('modeling');
    modeling.updateProperties(currentElement, properties);
  };

  return (
    <div>
      <Input ref={inputRef} onFocus={onBlur} value={selectedInfo?.name} />
      <Modal
        title="请选择表单"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Table
          rowSelection={{
            type: 'radio',
            ...rowSelection,
          }}
          rowKey="key"
          columns={columns}
          dataSource={tableData}
        />
      </Modal>
    </div>
  );
};

export default FormSetting;
